package com.medical.literature.document.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;

/**
 * 日期转换配置类
 */
@Configuration
public class DateConverterConfig implements WebMvcConfigurer {

    @Override
    public void addFormatters(FormatterRegistry registry) {
        // 注册String到LocalDate的转换器
        registry.addConverter(new Converter<String, LocalDate>() {
            @Override
            public LocalDate convert(String source) {
                if (source == null || source.trim().isEmpty()) {
                    return null;
                }
                
                try {
                    // 尝试解析 yyyy-MM-dd 格式
                    return LocalDate.parse(source, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                } catch (DateTimeParseException e) {
                    // 如果解析失败，尝试其他常见格式
                    try {
                        return LocalDate.parse(source, DateTimeFormatter.ISO_LOCAL_DATE);
                    } catch (DateTimeParseException e2) {
                        throw new IllegalArgumentException("无法解析日期: " + source, e2);
                    }
                }
            }
        });
    }
}